
<template>
  <div class="data-range">
    <a-table
      class="w-full h-full"
      v-if="table.dataSource.length > 0"
      :row-selection="table.rowSelection"
      :rowKey="record => record.id"
      :columns="table.columns"
      :data-source="table.dataSource"
      :defaultExpandAllRows="true"
      :scroll="{ y: 380 }"
      :pagination="false"
      bordered
    >
      <template slot="Title">
        <div class="title-button">
          <span>数据范围</span>
          <a-button @click="saveData" type="primary">保存</a-button>
        </div>
      </template>
    </a-table>
  </div>
</template>

<script>
import orupService from '@/api/orupService'
import moment from 'moment'

const columns = [
  {
    dataIndex: 'name',
    scopedSlots: { title: 'Title' },
    width: '100%'
  }
]

export default {
  name: 'DataRange',

  data () {
    return {
      filter: {
        filterText: '',
        pageIndex: 1,
        pageSize: 10
      },
      ids: [],
      table: {
        columns: columns,
        dataSource: [],
        rowSelection: {
          selectedRowKeys: [],
          onChange: (selectedRowKeys) => {
            this.table.rowSelection.selectedRowKeys = selectedRowKeys
          },
          getCheckboxProps: (record) => {
            if (record.check) {
              this.table.rowSelection.selectedRowKeys.push(record.id)
              this.ids = this.table.rowSelection.selectedRowKeys
            }
            return ({
              props: {
                // defaultChecked: record.check === true
              }
            })
          }
        }
      }
    }
  },

  props: {
    userId: {
      type: String,
      default: () => ('')
    }
  },

  watch: {
    userId (newId, oldId) {
      this.loadData(newId)
    }
  },

  mounted () {
    this.loadData(this.userId)
  },

  methods: {
    moment,
    async loadData (id) {
      this.table.dataSource = []
      this.table.dataSource = await orupService.userPermissionManageTreeDataQuery(id)
    },
    saveData () {
      const newKeys = this.table.rowSelection.selectedRowKeys
      const cancelIds = this.ids.filter((item) => !this.table.rowSelection.selectedRowKeys.includes(item))
      const params = {
        userId: this.userId,
        dicIds: newKeys.length ? newKeys : null,
        cancelIds: cancelIds.length ? cancelIds : null
      }
      orupService.userPermissionManageDataAdd(params).then(res => {
        this.$message.success('保存成功!')
        this.loadData(this.userId)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.title-button {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
/deep/ .ant-table-header-column {
  width: 100%;
}

</style>
